package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional  //添加事务
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public void submit(Orders orders) {
        // TODO 1.查询一个基础的数据（用户user，地址addressBook,订单orderId）
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId); //获取用户对象
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());//获取地址对象
        long orderId = IdWorker.getId();//雪花算法生成订单Id
        BigDecimal total = new BigDecimal(0);//总金额
        // TODO 2.封装List<OrderDetail> 对象的数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //查询用户购物车  TODO 处理订单项
        List<ShoppingCart> shoppingCartList = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, userId)
                .list();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setName(cart.getName());
            orderDetail.setImage(cart.getImage());
            orderDetail.setAmount(cart.getAmount());
            //计算单个菜品金额 单价 * 数量
            BigDecimal price = orderDetail.getAmount().multiply(new BigDecimal(cart.getNumber()));
            //把所有菜品金额加起来
            total = total.add(price);
            orderDetailList.add(orderDetail);
        }
        //TODO 3.封装order对象的数据   处理订单
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);//1待付款 2带派送 3已派送 4已完成 5已取消
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setAmount(total);
        orders.setId(orderId);
        this.save(orders);//保存订单
        orderDetailService.saveBatch(orderDetailList);//保存订单项
        //TODO 4.最后清空购物车
        shoppingCartService.lambdaUpdate()
                .eq(ShoppingCart::getUserId, userId)
                .remove();
    }
    //移动端显示订单详细信息
    @Override
    public Page<OrdersDto> pageWithDetail(Integer page, Integer pageSize) {
        Page<Orders> pageInfo =new Page(page,pageSize);
        Long userId = BaseContext.getCurrentId();
        return ordersMapper.pageWithDetail(pageInfo ,userId);
    }
}
